package org.loong.crypto.extension.crmf.jce;

import java.security.NoSuchAlgorithmException;

import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.cert.crmf.CRMFException;
import org.bouncycastle.cert.crmf.PKMACValuesCalculator;
import org.loong.crypto.core.algorithm.HmacAlgorithm;
import org.loong.crypto.core.algorithm.MessageDigestAlgorithm;
import org.loong.crypto.core.params.HmacParameters;
import org.loong.crypto.service.CryptoService;

public class JcePKMACValuesCalculator implements PKMACValuesCalculator {

    private CryptoService cryptoService;
    
    private AlgorithmIdentifier digestAlg;
    
    private AlgorithmIdentifier macAlg;
    
    public JcePKMACValuesCalculator(CryptoService cryptoService) {
        this.cryptoService = cryptoService;
    }

    @Override
    public void setup(AlgorithmIdentifier digestAlg, AlgorithmIdentifier macAlg) throws CRMFException {
        this.digestAlg = digestAlg;
        this.macAlg = macAlg;
    }

    @Override
    public byte[] calculateDigest(byte[] data) throws CRMFException {
        try {
            final MessageDigestAlgorithm digestAlgorithm = MessageDigestAlgorithm.findByAlgorithmId(digestAlg);
            return cryptoService.digest(digestAlgorithm, data);
        } catch (NoSuchAlgorithmException e) {
            throw new CRMFException(e.getMessage(), e);
        }
    }

    @Override
    public byte[] calculateMac(byte[] pwd, byte[] data) throws CRMFException {
        try {
            final HmacAlgorithm hmacAlgorithm = HmacAlgorithm.findByAlgorithmId(macAlg);
            return cryptoService.hmac(hmacAlgorithm, HmacParameters.builder().secret(pwd).build(), data);
        } catch (NoSuchAlgorithmException e) {
            throw new CRMFException(e.getMessage(), e);
        }
    }
}
